﻿using System;
using System.Text.RegularExpressions;
using System.Web;
using BO.Infrastructure.StaticData;
using BO.Infrastructure.Utils;
using BO.Solr;
using ChannelVN.Cached.UrlRewrite;
using GUI.Extensions;

namespace GUI.Pages.News
{
    public partial class Search : System.Web.UI.Page
    {
        private const int PageSize = 30;
        public string Keywords { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            var keywords = HttpUtility.UrlDecode(RequestExtensions.Keywords);
            if (!string.IsNullOrEmpty(keywords))
            {
                keywords = Keywords = Regex.Replace(keywords, "[_]+", " ");
                var containsPageIndex = RequestExtensions.ContainsPageIndex;
                var pageIndex = RequestExtensions.PageIndex;
                var searchResult = SolrBO.SearchNewsByKeywords(
                    keywords: keywords,
                    pageIndex: pageIndex,
                    pageSize: PageSize);

                ctrListNewsByTag.Visible = ctrListNewsByTag.DataBind(searchResult.response.docs, keywords);

                ltrTitle.Text = keywords;

                ctrPaging.SumPage = (int)Math.Ceiling((double)searchResult.response.numFound / PageSize);
                ctrPaging.LinkSite = RequestExtensions.Url;
                ctrPaging.Padding(pageIndex);

                #region Title/MetaData
                var extraText = containsPageIndex ? string.Format(" | page {0}", pageIndex) : string.Empty;
                var unsignKeywords = PresentationUtils.UnicodeToKoDau(keywords);
                var metaKeywords = string.Format("{0},{1}", keywords, unsignKeywords);
                var title = string.Format("{0}{1} | tin tức mới nhất về {1} | tin nhanh mới cập nhật về {1}", keywords.Equals(unsignKeywords, StringComparison.InvariantCultureIgnoreCase) ? string.Empty : string.Format("{0} | ", keywords), unsignKeywords);
                Page.Header.Title = string.Format("{0} | soha.vn{1}", title, extraText);
                PresentationUtils.AddMeta(Page, DefinedConstants.MetaAttributes.Description.Id, DefinedConstants.MetaAttributes.Description.Name, keywords + extraText);
                PresentationUtils.AddMeta(Page, DefinedConstants.MetaAttributes.Keywords.Id, DefinedConstants.MetaAttributes.Keywords.Name, metaKeywords);
                PresentationUtils.AddMeta(Page, DefinedConstants.MetaAttributes.NewsKeywords.Id, DefinedConstants.MetaAttributes.NewsKeywords.Name, metaKeywords);
                #endregion

                return;
            }
            _301Redirection.RedirectTo("/");
        }
    }
}